/* TestRunner.js
 *
 * Copyright 2006, Tim Dwelle.
 *
 * Licensed under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in
 * compliance with the License.  You may obtain a copy of
 * the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in
 * writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied.  See
 * the License for the specific language governing
 * permissions and limitations under the License.
 *
 */

$package("dowry.test");

$import("dowry.test.Logger");

/**
 * TestRunner executes the specified suite of tests and
 * reports the results to the provided logger.
 *
 * <p>
 * This particular implemenation of the unit testing
 * framework was strongly influenced by the excellent unit
 * testing framework in <a href="http://script.aculo.us/">
 * Scriptaculous</a>.  In fact, originally I planned to
 * just use their unit testing framework, until I started
 * to notice occasional situations where the Prototype/
 * Scriptaculous dependencies were actually influencing the
 * test results.
 * </p>
 *
 */
$class("TestRunner").$as(
{
    /**
     * Index of the currently running test.
     *
     */
    _currentTest : 0,

    /**
     * Logger to report the test results with.
     *
     */
    _logger : null,

    /**
     * The object representing the suite of tests to
     * execute.
     *
     */
    _obj : null,

    /**
     * Array of tests to be run.
     *
     */
    _tests : null,

    /**
     * Constructs a new TestRunner.
     *
     * @param obj     the object representing the suite of
     *                tests to execute
     *
     */
    TestRunner : function(obj)
    {
        if (obj == null)
        {
            obj = this.loadObject();
        }

        if (obj != null)
        {
            this._tests = new Array();
            this._obj = obj;

            var re = /^test/;

            for (var feature in obj)
            {
                if (re.test(feature))
                {
                    var test = { name: feature,
                                 assertions : 0,
                                 failures: 0,
                                 errors : 0,
                                 messages: [],
                                 func : obj[feature] };

                    this._tests[this._tests.length] = test;
                }
            }

            setTimeout(this.runTests, 1000);
        }
    },

    /**
     * Checks to make sure that the page is loaded and
     * TestRunner setup to the point where we can start
     * our testing.
     *
     * @return   true, if ready to start running tests;
     *           false otherwise
     *
     */
    isReady : function()
    {
        var rc = false;

        if (this._logger != null)
        {
            rc = true;
        }
        else if (document != null &&
                 document.body != null)
        {
            this._logger = new dowry.test.Logger();
            rc = true;
        }

        return rc;
    },

    /**
     * Attempts to loads the object from the query string
     * parameters (ie.
     * <code>TestRunner.html?class=dowry.test.MyTest</code>.
     *
     * @return  the object instance, if it can be loaded
     *          from the query string
     *
     */
    loadObject : function()
    {
        var obj = null;

        // get the raw query string
        var s = document.location.search;
        if (s)
        {
            s = s.match(/^\??(.*)$/)[1];
            if (s)
            {
                var c = $classLoader.loadClass(s);
                if (c)
                {
                    obj = new c();
                }
            }
        }

        return obj;
    },

    /**
     * Hook for the start of the suite of tests.  By
     * default, this logs the name of the test (if
     * provided) by calling <code>logger.title()</code>.
     *
     */
    onStart : function()
    {
        if (this._obj.$class)
        {
            this._logger.title(this._obj.$class);
        }
    },

    /**
     * Hook for the completion of the suite of tests.  By
     * default, this reports a summary to the logger by
     * calling <code>logger.summary()</code>.
     *
     */
    onFinish : function()
    {
        var tests      = this._tests;
        var len        = tests.length;
        var assertions = 0;
        var failures   = 0;
        var errors     = 0;

        for (var i=0; i < len; i++)
        {
            assertions += tests[i].assertions;
            failures   += tests[i].failures;
            errors     += tests[i].errors;
        }

        var msg = len +
                  " tests, " +
                  assertions +
                  " assertions, " +
                  failures +
                  " failures, " +
                  errors +
                  " errors";

        this._logger.summary(msg);
    },


    /**
     * Hook for the start of an individual test.  By
     * default, this reports the start to the logger by
     * calling <code>logger.start()</code>.
     *
     * @param test  object representing the test being
     *              started
     *
     */
    onTestStart : function(test)
    {
        this._logger.start(test.name);
    },

    /**
     * Hook for reporting that a test is waiting.  By
     * default, this sens a message to the logger by
     * calling <code>logger.message()</code>.
     *
     * @param test  object representing the test that is
     *              waiting
     *
     */
    onTestWait : function(test)
    {
        var timeToWait = test.timeToWait || 1000;
        this._logger.message("Waiting for " + timeToWait + "ms");
    },

    /**
     * Hook for the completion of an individual test.  By
     * default, this reports the completion to the logger by
     * calling <code>logger.finish()</code>.
     *
     * @param test  object representing the test being
     *              completed
     *
     */
    onTestFinish : function(test)
    {
        var s = "passed";

        if (test.errors > 0)
        {
            s = "error";
        }
        else if (test.failures > 0)
        {
            s = "failed";
        }

        var msg = test.assertions +
                  " assertions, " +
                  test.failures   +
                  " failures, "   +
                  test.errors     +
                  " errors\n"     +
                  test.messages.join("\n");

        this._logger.finish(s, msg);
    },

    /**
     * Executes the suite of tests.
     *
     */
    runTests : function()
    {
        if (this.isReady())
        {
            var obj = this._obj;
            var test = this._tests[this._currentTest];

            if (this._currentTest == 0 &&
                (obj._currentTest == null ||
                 !obj._currentTest.isWaiting))
            {
                this.onStart();
            }

            if (test != null)
            {
                if (obj._currentTest == null ||
                    !obj._currentTest.isWaiting)
                {
                    this.onTestStart(test);
                }

                this.runTest(test);

                if (obj._currentTest != null &&
                    obj._currentTest.isWaiting)
                {
                    this.onTestWait(test);

                    var timeToWait = test.timeToWait || 1000;
                    test.timeToWait = null;

                    setTimeout(this.runTests, timeToWait);
                }
                else
                {
                    this.onTestFinish(test);
                    this._currentTest++;
                    this.runTests();
                }
            }
            else
            {
                this.onFinish();
            }
        }
        else
        {
            setTimeout(this.runTests, 1000);
        }
    },

    /**
     * Executes an individual test.
     *
     * @param test  object representing the test to run
     *
     */
    runTest : function(test)
    {
        var obj = this._obj;

        try
        {
            if (obj._currentTest == null ||
                !obj._currentTest.isWaiting)
            {
                obj._currentTest = test;

                if (obj.setup)
                {
                    obj.setup();
                }
            }

            test.isWaiting = false;

            if (test.func)
            {
                test.func.call();
            }
        }
        catch(e)
        {
            if (obj._error)
            {
                obj._error(e);
            }
        }

        try
        {
            if (!test.isWaiting)
            {
                if (obj.teardown)
                {
                    obj.teardown();
                }
            }
        }
        catch(e)
        {
            if (obj._error)
            {
                obj._error(e);
            }
        }
    }
});